__author__ = 'v-yuezh'
import sys
import urllib.request
import re
from PyQt5.QtCore import QDir, Qt
from PyQt5.QtGui import QFont, QPalette
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QBrush, QColor, QFont, QDesktopServices
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
        QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout, QVBoxLayout, QTableView, QHeaderView,
        QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton)


class SpiderDialog(QDialog):
    def __init__(self, parent=None):
        super(SpiderDialog, self).__init__(parent)

        layout = QVBoxLayout()

        self.btn_search = QPushButton()
        self.btn_search.setText("Search")
        self.btn_search.clicked.connect(self.onSearchBtnClicked)

        self.dataView = QTableView()
        self.model = QStandardItemModel(3, 0, self)


        self.dataView.setModel(self.model)
        self.dataView.setFont(QFont("Simsun", 9))
        layout.addWidget(self.btn_search)
        layout.addWidget(self.dataView)

        self.setLayout(layout)

        self.setGeometry(50, 50, 400, 400)

    def getHtml(self, url):
        page = urllib.request.urlopen(url)
        html = page.read().decode("gb2312")
        return html

    def getData(self, html):

        imglist = re.findall('file=M.\d{10}.A">(.*?)</a>',html)
        #imglist = re.findall('shtml.*?>(.*?)</a>',html)
        return imglist

    def onSearchBtnClicked(self):
        html = self.getHtml("http://bbs.ustc.edu.cn/cgi/bbstdoc?board=Job")
        jobdata = self.getData(html)

        #self.dataView.horizontalHeader().setResizeMode(0, QHeaderView.Fixed)


        self.model.setHorizontalHeaderItem(0, QStandardItem("USTC BBS"))

        for i in range(len(jobdata)):
            self.model.setItem(i, 0, QStandardItem(jobdata[i].replace('&nbsp', '')))

        self.dataView.setColumnWidth(0, 300)

        html = self.getHtml("http://bbs.ustc.edu.cn/cgi/bbstdoc?board=Intern")
        jobdata = self.getData(html)

        #self.dataView.horizontalHeader().setResizeMode(0, QHeaderView.Fixed)


        self.model.setHorizontalHeaderItem(1, QStandardItem("Intern"))

        for i in range(len(jobdata)):
            self.model.setItem(i, 1, QStandardItem(jobdata[i].replace('&nbsp', '')))

        self.dataView.setColumnWidth(1, 300)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    dialog = SpiderDialog()
    dialog.show()
    sys.exit(app.exec_())